package com.commissarxiii 
{
	import com.commissarxiii.loader.LoaderItem;
	import com.commissarxiii.loader.LoaderQueue;
	import flash.external.ExternalInterface;
	/**
	 * FlashLoader handles the loading of files and passing the loaded data
	 * back to JavaScript. Files can be loaded individually or added to a 
	 * queue to be loaded later.
	 * 
	 * @author Benjamin Van Heest
	 * @version 1.0
	 */
	public class FlashLoader 
	{
		/**
		 * LoaderQueue instance used for loading multiple LoaderItems.
		 */
		private var _queue:LoaderQueue;
		
		/**
		 * Create a new FlashLoader instance.
		 */
		public function FlashLoader() 
		{
			init();
		}
		
		/**
		 * Initialize FlashLoader. Expose public methods to JavaScript via
		 * ExternalInterface.
		 */
		private function init():void
		{
			_queue = new LoaderQueue();
			
			if (ExternalInterface.available)
			{
				// Expose methods to JS
				ExternalInterface.addCallback('addToQueue', addToQueue);
				ExternalInterface.addCallback('loadQueue', loadQueue);
				ExternalInterface.addCallback('load', load);
			}
		}
		
		/**
		 * Loads a single file and optionally sends the loaded data to the provided
		 * JavaScript callback.
		 * 
		 * @param	url URL of the file to load
		 * @param	jsCallback JavaScript method called when data is loaded
		 */
		public function load(url:String, jsCallback:String = null):void
		{
			var loaderItem:LoaderItem = new LoaderItem(url, jsCallback);
			loaderItem.load();
		}
		
		/**
		 * Adds a file and optional JavaScript callback to the loader queue. Note: this callback will be
		 * called when this item is loaded, not the entire queue.
		 * 
		 * @param	url URL of the file to load
		 * @param	jsCallback JavaScript method called when data is loaded
		 */
		public function addToQueue(url:String, jsCallback:String = null):void
		{
			var loaderItem:LoaderItem = new LoaderItem(url, jsCallback);
			_queue.addItem(loaderItem);
		}
		
		/**
		 * Load all items that have been added to the queue and call optional JavaScript callback
		 * when all items have been loaded. By default, the queue loads one item at a time (synchronously). Increase
		 * the maximum concurrent downloads to load more than one file at a time (asynchronously).
		 * 
		 * @param	jsCallback JavaScript method called when entire queue is loaded
		 * @param	maxConcurrent Maximum concurrent loads. Use 1 for synchronous queue loading or a higher value for
		 * 			asynchronous loading. Caution: A high number of concurrent loads may affect performance.
		 */
		public function loadQueue(jsCallback:String = null, maxConcurrent:int = 1):void
		{
			_queue.load(jsCallback, maxConcurrent);
		}
	}
}